<?php

namespace App\Jobs;

use App\Admin\Services\GoodService;
use App\Model\ExportGoodJobDetail;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Promise;

class DownImageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $jobDetailId;

    /**
     * Create a new job instance.
     *
     * @param int $jobDetailId
     */
    public function __construct(int $jobDetailId)
    {
        //
        $this->jobDetailId = $jobDetailId;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \Exception
     */
    public function handle()
    {
        if ($this->attempts() > 3) {
            return;
        }

        $job = ExportGoodJobDetail::query()->with('good')->find($this->jobDetailId);
        $job->is_handle = 1;

        $client = new Client(['base_uri' => 'http://img.susan.jiandanshang.com']);

        $promises = [];
        if ($job->good && $job->good->goods_img_url) {
            if (!$job->goods_image = $this->checkImage($job->good->goods_img_url)) {
                $promises['goods_image'] = $client->getAsync('/upload/w_66/' . $job->good->goods_img_url);
            }
        }

        if ($job->good && $job->good->amazon_img_url) {
            if (!$job->amazon_image = $this->checkImage($job->good->amazon_img_url)) {
                $promises['amazon_image'] = $client->getAsync('/upload/w_66/' . $job->good->amazon_img_url);
            }

        }


        if ($promises) {
            try {
                $results = Promise\unwrap($promises);
                if (!empty($results['goods_image'])) {
                    $goodsImageResponse = $results['goods_image'];
                    if ($goodsImageResponse instanceof Response && 200 == $goodsImageResponse->getStatusCode()) {
                        $goodImagePath = $this->storageImage($job->good->goods_img_url, $goodsImageResponse->getBody()->getContents());
                        if ($goodImagePath) {
                            $job->goods_image = $goodImagePath;
                        }
                    }
                }

                if (!empty($results['amazon_image'])) {

                    $goodsImageResponse = $results['amazon_image'];
                    if ($goodsImageResponse instanceof Response && 200 == $goodsImageResponse->getStatusCode()) {
                        $amazonImagePath = $this->storageImage($job->good->amazon_img_url, $goodsImageResponse->getBody()->getContents());
                        if ($amazonImagePath) {
                            $job->amazon_image = $amazonImagePath;
                        }

                    }
                }
            } catch (\Throwable $e) {
                $job->is_handle = 2;
            }



        }

        $job->save();

        // 如果已经全部处理完成则可以进行导出处理
        if (!ExportGoodJobDetail::query()->where('job_id', $job->job_id)
            ->where('is_handle', 0)->count()) {
            // 导出，导出成功或者失败删除相关的文件夹
            app(GoodService::class)->exportGood($job->job_id);
        }
    }


    /**
     * @desc 判断是图片是否存在
     *
     * @param string $imageUrl
     *
     * @return bool|string
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-18 17:51:47
     */
    public function checkImage(string $imageUrl)
    {
        $filename = md5($imageUrl) . '.jpg';
        $path = 'goods/' . $filename;

        if (Storage::disk('local')->exists($path)) {
            return $path;
        }
        return false;
    }

    /**
     * @desc 保存图片
     *
     * @param string $imageUrl
     * @param string $content
     *
     * @return bool|string
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-18 17:48:36
     */
    public function storageImage(string $imageUrl, string $content)
    {

        $filename = md5($imageUrl) . '.jpg';
        $path = 'goods/' . $filename;

        if (Storage::disk('local')->put($path, $content)) {
            return $path;
        }

        return false;
    }

}
